<?php
/**
 * User.php
 * Created by PhpStorm.
 * User: 江小波
 * Date: 2019/6/5
 * Time: 13:10
 */
namespace app\common\simple_rbac;

use app\common\Singleton;

class User
{
    use Singleton;

    /**
     * 登录授权
     * @param string $username
     * @param string $password
     * @param array $extend_param
     * @throws \Exception
     */
    public function auth($username="",$password="",$extend_param=[])
    {
        // 查询用户
        $user = Model::getInstance()->getUserByUsername($username);
        if(empty($user['id'])){
            throw new \Exception("账户未知！",1);
        }
        if( $user['password'] != md5($password) ){
            throw new \Exception("密码错误！",2);
        }
        if( $user['lock'] == 1 ){
            throw new \Exception("该账户被冻结，请联系管理员！",3);
        }
        if( $user['platform_id'] != config('platform_info.id') ){
            throw new \Exception("该账户不属于该平台！",4);
        }
        if(empty($user['roles'])){
            throw new \Exception("账户角色未绑定，请联系管理员！",5);
        }
        $roles = explode(",",trim($user['roles'],","));
        // 判断该登录用户是否是超级管理员
        $user['is_super_admin'] = Model::getInstance()->checkSuperAdminByRoles($roles);
        // 如果不是超级会员查询用户权限节点
        if(!$user['is_super_admin'])
        {
            $roleNodes = Model::getInstance()->getAccessNodesByRoleIds($roles);
            $nodes = [];
            if(!empty($user['nodes']))
            {
                $nodes[] = $user['nodes'];
            }
            if(!empty($roleNodes))
            {
                $nodes[] = implode(",",$roleNodes);
            }
            $user['nodes'] = Model::getInstance()->getNotRepeatNodes($nodes);
        }else{
            // 超级管理员不需要权限节点
            unset($user['nodes']);
        }
        // 去除敏感信息
        unset($user['pawrd'],$user['password']);

        // 登录成功

        return $user;
    }
}